package com.llkj.qingnianguoxue.home;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.kk.taurus.playerbase.assist.OnVideoViewEventHandler;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.event.OnPlayerEventListener;
import com.kk.taurus.playerbase.receiver.ReceiverGroup;
import com.kk.taurus.playerbase.render.AspectRatio;
import com.kk.taurus.playerbase.widget.BaseVideoView;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.HotRankingAdapter;
import com.llkj.qingnianguoxue.adapter.VideoDetailCommentAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CommentListBean;
import com.llkj.qingnianguoxue.bean.HotRankingBean;
import com.llkj.qingnianguoxue.bean.ResponseBean;
import com.llkj.qingnianguoxue.bean.VideoDetailBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.mine.BalanceActivity;
import com.llkj.qingnianguoxue.mine.PayOrderActivity;
import com.llkj.qingnianguoxue.mine.ShopCartActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.MyShare;
import com.llkj.qingnianguoxue.util.PlayingTimeListener;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.videoplayer.bean.VideoBean;
import com.llkj.qingnianguoxue.videoplayer.corver.ControllerCover;
import com.llkj.qingnianguoxue.videoplayer.corver.PayCorver;
import com.llkj.qingnianguoxue.videoplayer.play.DataInter;
import com.llkj.qingnianguoxue.videoplayer.play.MonitorDataProvider;
import com.llkj.qingnianguoxue.videoplayer.play.ReceiverGroupManager;
import com.llkj.qingnianguoxue.videoplayer.utils.PUtil;
import com.pingplusplus.android.Pingpp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.kk.taurus.playerbase.player.IPlayer.STATE_PAUSED;
import static com.llkj.qingnianguoxue.mine.PayOrderActivity.REQUEST_ORDER_PAY;
import static com.llkj.qingnianguoxue.videoplayer.play.DataInter.ReceiverKey.KEY_CONTROLLER_COVER;
import static com.llkj.qingnianguoxue.videoplayer.play.DataInter.ReceiverKey.KEY_PAY_COVER;

/**
 * 视频详情
 */
public class VideoDetailActivity extends BaseActivity implements MyShare.ShareResultCallback,OnPlayerEventListener {
    private static final int REQUEST_LOGIN_CODE = 6666;
    private static final int REQUEST_CART_CODE = 8974;
    private static final int REQUEST_VIDEO_CODE = 9977;
    private static final int REQUEST_SUBSCRIBE_CODE = 8374;
    private static final String SEEK_POSITION_KEY = "SEEK_POSITION_KEY";
    private static final int REQUEST_EDIT_COMMENT_CODE = 7985;
    public static final String REFRESH_STATE = "refresh_state";

    @BindView(R.id.video_title)
    FrameLayout flTopView;
    @BindView(R.id.tv_shops_count)
    TextView tvShopCount;
    @BindView(R.id.baseVideoView)
    BaseVideoView mVideoView;
    private boolean userPause;
    private boolean isLandscape;
    private ReceiverGroup mReceiverGroup;

    @BindView(R.id.flVideoContainer)
    FrameLayout mFlVideoContainer;
    @BindView(R.id.fl_video_cover)
    FrameLayout flVideoCover;
    @BindView(R.id.iv_video_cover)
    ImageView ivVideoCover;

    @BindView(R.id.scrollView_bottom)
    NestedScrollView scrollViewBottom;
    private int mSeekPosition;

    @BindView(R.id.tv_count)
    TextView tvCount;//报名人数
    @BindView(R.id.tv_video_category)
    TextView tvVedioCategory;//视频分类
    @BindView(R.id.tv_video_title)
    TextView tvVedioTitle;//视频题目
    @BindView(R.id.tv_duration)
    TextView tvVedioDuration;//视频时长

    @BindView(R.id.iv_head)
    ImageView ivHead;//头像
    @BindView(R.id.tv_name)
    TextView tvName;//大师名字
    @BindView(R.id.tv_subscribe)
    TextView tvSubscrib;//订阅按钮
    @BindView(R.id.tv_video_detail)
    TextView tvVideoDetial;//视频详情
    @BindView(R.id.webView)
    WebView wvDescription;//图书描述

    @BindView(R.id.tv_comment_count)
    TextView tvCommentCount;//热闹评论数量
    @BindView(R.id.lv_comment)
    RecyclerView lvComment;//评论列表
    private VideoDetailCommentAdapter commentAdapter;//评论适配器
    private List<CommentListBean.CommentBean> commentData;//评论数据
    @BindView(R.id.lv_recommend)
    RecyclerView lvRecommned;//推荐列表
    private HotRankingAdapter rankingAdapter;
    private List<HotRankingBean.RankingBean> mRankData;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottomBtn;//底部按钮

    @BindView(R.id.ll_praise)
    LinearLayout llPraise;//点赞
    @BindView(R.id.tv_add_cart)
    TextView tvAddCart;//加入购物车
    @BindView(R.id.tv_pay)
    TextView tvBuy;//购买

    private String mDetailId, mArtistId, mCartId;//详情视频id,大师id,购物车id
    private String mPayMoney;//支付金额
    private int mCurrentPosition, mShopCount;//购物车
    private String mVideoUrl;//視頻播放地址
    private boolean isAddCart = false;//false未加入
    private boolean isBuy;//是否购买了
    private boolean isResult;//控制是否返回
    private float mPlayPercentage;//视频播放进度
    private String mCorverUrl;//视频封面url
    private int mBuyCount;//购买数量
    private boolean isEnable = true;
    private boolean bootomGone;
    private String masterId;
    private int isMember;
    private HotRankingBean.RankingBean mVedioBean;//保存视频信息
    private PayCorver mPayCorver;
    private long mPlayTime;//观看时长
    private int mPrePlayTime;//上次播放时间位置
    private int mCommentsCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
        setTitle("详情", true, TITLE_TYPE_IMG, R.drawable.icon_back, true,TITLE_TYPE_IMG, R.drawable.icon_video_detail_cart);

        ButterKnife.bind(this);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        initView();
        initVideoView();
        initListener();

        if (bundle != null) {
            mDetailId = bundle.getString("id");
            bootomGone = bundle.getBoolean(ConstantUserInfo.GONE, false);
        }
        if (bootomGone) {
            llBottomBtn.setVisibility(View.GONE);
        }

        getVideoDetail();
        setWebview();
    }

    private void initView() {
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,flTopView,R.color.gray_bar);
        tvSubscrib.setVisibility(View.GONE);
        lvComment.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        lvComment.setFocusable(false);
        lvComment.setNestedScrollingEnabled(false);
        commentData = new ArrayList<>();
        commentAdapter = new VideoDetailCommentAdapter(R.layout.item_video_detail_comment, commentData);
        lvComment.setAdapter(commentAdapter);

        lvRecommned.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        lvRecommned.setFocusable(false);
        lvRecommned.setNestedScrollingEnabled(false);
        mRankData = new ArrayList<>();
        rankingAdapter = new HotRankingAdapter(R.layout.item_hot_ranking, mRankData, null);
        rankingAdapter.setType(3);
        lvRecommned.setAdapter(rankingAdapter);

        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (isLogin) {
            tvShopCount.setVisibility(View.VISIBLE);
        }

    }

    private void initVideoView(){
        mVideoView.setAspectRatio(AspectRatio.AspectRatio_16_9);
        mVideoView.setAspectRatio(AspectRatio.AspectRatio_FILL_PARENT);
        mVideoView.setOnPlayerEventListener(this);
        mVideoView.setEventHandler(mOnEventAssistHandler);

        mReceiverGroup = ReceiverGroupManager.get().getReceiverGroup(this, null);
        mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_NETWORK_RESOURCE, true);
        mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_CONTROLLER_TOP_ENABLE, true);
        mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_IS_HAS_NEXT, true);
        mVideoView.setReceiverGroup(mReceiverGroup);

        mPayCorver = mReceiverGroup.getReceiver(KEY_PAY_COVER);
        mPayCorver.getView().findViewById(R.id.tv_look_buy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startPay();
            }
        });
        mPayCorver.setPlayListener(new PlayingTimeListener() {
            @Override
            public void isPlay(int currPlay) {
                if(mPrePlayTime!=currPlay){
                    mPlayTime++;
                }
                mPrePlayTime = currPlay;
            }
        });
        updateVideo(false);
    }

    /**
     * 设置WebView
     */
    private void setWebview() {
        WebSettings settings = wvDescription.getSettings();
        //支持javascript
        settings.setJavaScriptEnabled(true);
        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);

        String webUrl = String.format(HttpMethod.ARTIST_DETAILS_ABSTRACT,mDetailId,"3");
        wvDescription.loadUrl(webUrl);
    }

    private void initListener() {
        lvRecommned.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mCurrentPosition = i;
                //调取详情接口
                HotRankingBean.RankingBean item = mRankData.get(i);
                mDetailId = item.getId();
                getVideoDetail();
            }
        });
    }

    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        if(ivRight.getVisibility()==View.VISIBLE){
            boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
            if (!isLogin) {
                dialogConfirm(null, null, null, null).show();
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString("need_result", "1");
            startActivityForResult(ShopCartActivity.class, bundle, REQUEST_CART_CODE);
        }

    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    @OnClick({R.id.ll_share, R.id.ll_praise, R.id.iv_head, R.id.tv_name, R.id.tv_subscribe, R.id.tv_edit_comment, R.id.tv_more_comment, R.id.tv_add_cart, R.id.tv_pay, R.id.fl_video_cover})
    public void onClick(View v) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        Bundle bundle = null;

        switch (v.getId()) {
            case R.id.ll_share://分享
                String videoTitle = tvVedioTitle.getText().toString();
                String linkUrl = String.format(HttpMethod.SHARE_VIDEO, mDetailId);
                String description = tvVideoDetial.getText().toString();
                DialogUtil.showShareDialog(this, videoTitle, description, mCorverUrl, linkUrl, this);
                break;
            case R.id.ll_praise:
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                int type = llPraise.isSelected() ? 2 : 1;
                if (type != 0) {
                    setVideoPraise(type);
                }
                break;
            case R.id.iv_head://大师头像
            case R.id.tv_name:
                bundle = new Bundle();
                bundle.putString("id", mArtistId);
                startActivityForResult(MasterDetailActivity.class, bundle, REQUEST_SUBSCRIBE_CODE);
                break;
            case R.id.tv_subscribe://订阅按钮
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                if (tvSubscrib.isSelected()) {
                    return;
                }
                if (!isEnable) {
                    ToastUtil.makeShortText(this, "已订阅");
                    return;
                }
                if (isMember == 1){
                    orderMaster();
                }else {
                    bundle = new Bundle();
                    bundle.putString("id", mArtistId);
                    startActivityForResult(MasterSubscribeActivity.class, bundle, REQUEST_SUBSCRIBE_CODE);
                }
                break;
            case R.id.tv_edit_comment://写评论
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                bundle = new Bundle();
                bundle.putString("id", mDetailId);
                startActivityForResult(EditCommentActivity.class, bundle, REQUEST_EDIT_COMMENT_CODE);
                break;
            case R.id.tv_more_comment://更多评论
                bundle = new Bundle();
                bundle.putString("id", mDetailId);
                startActivityForResult(CommentListActivity.class, bundle, REQUEST_EDIT_COMMENT_CODE);
                break;
            case R.id.tv_add_cart://加入购物车
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                if (tvAddCart.isSelected()) {
                    return;
                }
                if (!isAddCart) {//加入购物车
                    addCart();
                } else {//移除购物车
                    delCart();
                }
                break;
            case R.id.tv_pay://购买
                startPay();
                break;
            case R.id.fl_video_cover:
                flVideoCover.setVisibility(View.GONE);
                if(mVideoView != null){
                    mVideoView.start();
                }
                break;
        }
    }

    private void startPay(){
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        if (!isLogin) {
            dialogConfirm(null, null, null, null).show();
            return;
        }
        List<HotRankingBean.RankingBean> checkShopsData = new ArrayList<>();
        checkShopsData.add(mVedioBean);
        Bundle bundle = new Bundle();
        bundle.putSerializable("checkShops", (Serializable) checkShopsData);
        bundle.putString("shopsId",mDetailId);
        bundle.putString("categoryType","ViDeoDetail");
        try {
            bundle.putFloat("payMoney",Float.parseFloat(mPayMoney));
        }catch (Exception e){}
        startActivityForResult(PayOrderActivity.class, bundle, REQUEST_ORDER_PAY);
    }

    @Override
    public void onPlayerEvent(int eventCode, Bundle bundle) {

    }

    private void orderMaster() {
        HttpMethod.orderApp(this, this, "1", masterId, "-1", "-1", "-1");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (REQUEST_LOGIN_CODE == requestCode && resultCode == Activity.RESULT_OK) {
            getVideoDetail();//调用详情
        } else if (REQUEST_EDIT_COMMENT_CODE == requestCode && resultCode == Activity.RESULT_OK) {//评论后返回处理
            if (data != null && data.hasExtra("comment_data")) {
                List<CommentListBean.CommentBean> dataList = (List<CommentListBean.CommentBean>) data.getSerializableExtra("comment_data");
                if (dataList != null) {
                    if (data.getBooleanExtra("many", false)) {//处理从评论列表发布返回
                        mCommentsCount = dataList.size();
                        commentData.clear();
                    }else{
                        mCommentsCount++;
                    }
                    if (commentData.size() >= 5) {//处理直接发布一条评论
                        commentData.remove(commentData.size() - 1);
                    }
                    try {
                        commentData.addAll(0, dataList);
                        commentAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                tvCommentCount.setText("热门评论（"+mCommentsCount+"）");
            }
        } else if (resultCode == RESULT_OK && requestCode == REQUEST_CART_CODE) {//从购物车返回
            if (data != null && data.hasExtra("num")) {
                tvShopCount.setText(data.getStringExtra("num"));//购物车数量
            }
            try {
                if (data != null && data.hasExtra("result")) {
                    String[] list = data.getStringExtra("result").split(",");
                    List<String> myList = new ArrayList();
                    Collections.addAll(myList, list);

                    if (myList.contains(mDetailId)) {
                        setPayVideoPlay();
                    }
                }

                if (data != null && data.hasExtra("del")) {
                    String[] list = data.getStringExtra("del").split(",");
                    List<String> myList = new ArrayList();
                    Collections.addAll(myList, list);

                    if (myList.contains(mDetailId)) {//该视频被删除购物车
                        removeCart();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (resultCode == RESULT_OK && REQUEST_SUBSCRIBE_CODE == requestCode) {
            tvSubscrib.setText("已订阅");
            buyVideoSucess();
            mBuyCount++;
            setBuyCountView();
        }else if(resultCode == RESULT_OK && REQUEST_ORDER_PAY == requestCode){
            buyVideoSucess();
            mBuyCount++;
            setBuyCountView();
        }
    }

    private void buyVideoSucess(){
        mPayCorver.isBuyVideo(true);
        if(View.VISIBLE==mPayCorver.getView().getVisibility()){
            mPayCorver.setCoverVisibility(View.GONE);
            mVideoView.resume();
        }
        flVideoCover.setVisibility(View.GONE);
        setPayVideoPlay();
    }

    private void setVideoPlayData(String title){
        VideoBean bean = new VideoBean();
        bean.setCover(mCorverUrl);
        bean.setPath(mVideoUrl);
        bean.setDisplayName(title);
        MonitorDataProvider dataProvider = new MonitorDataProvider(bean);
        mVideoView.setDataProvider(dataProvider);
        DataSource dataSource = new DataSource();
        mVideoView.setDataSource(dataSource);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_HANDPICK_VIDEO_DETAILS) {//视频详情
            VideoDetailBean detailBean = GsonUtil.GsonToBean(data, VideoDetailBean.class);
            if (detailBean != null) {
                mVedioBean = new HotRankingBean.RankingBean();
                mVedioBean.setId(detailBean.getVideo().getId());
                mVedioBean.setTitle(detailBean.getVideo().getTitle());
                mVedioBean.setImg(detailBean.getVideo().getImg());
                mVedioBean.setAbstractX(detailBean.getVideo().getAbstractX());
                mVedioBean.setShopping_id(detailBean.getShopping_id());

                //设置视频封面
                mCorverUrl = detailBean.getVideo().getImg();
                ImageLoadingUtil.loadingUrlCenterCrop(ivVideoCover,mCorverUrl);
                flVideoCover.setVisibility(View.VISIBLE);
                tvVedioTitle.setText(detailBean.getVideo().getTitle());
                tvTitle.setText(detailBean.getVideo().getTitle());
                try {
                    mBuyCount = Integer.parseInt(detailBean.getVideo().getOrder_num());
                }catch (Exception e){}

                setBuyCountView();

                mArtistId = detailBean.getVideo().getArtistId();
                //大师头像
                ImageLoadingUtil.loadingImg(ivHead, detailBean.getArtist().getImg(), 0);
                tvName.setText(detailBean.getArtist().getName());
                masterId = detailBean.getArtist().getId();
                isMember = detailBean.getIs_app();
                mPayMoney = detailBean.getVideo().getPrice();
                if (detailBean.getIs_app() == 1 || detailBean.getIs_artist() == 1 || detailBean.getIs_video() == 1) {//是 1否 2
                    isBuy = true;
                    if (detailBean.getIs_artist() == 1) {
                        tvSubscrib.setSelected(true);//订阅按钮
                        tvSubscrib.setText("已订阅");
                        isEnable = false;
                    }
                    llBottomBtn.setVisibility(View.GONE);
                } else {
                    llBottomBtn.setVisibility(View.VISIBLE);
                    tvBuy.setText("购买:￥" + mPayMoney+"银子");

                    if (!StringUtils.isEmpty(detailBean.getShopping_id())) {
                        tvAddCart.setText("移除购物车");
                        mCartId = detailBean.getShopping_id();
                        isAddCart = true;
                    }
                }

                try {
                    if(Float.parseFloat(mPayMoney)==0){
                        llBottomBtn.setVisibility(View.GONE);
                        ivRight.setVisibility(View.GONE);
                        tvShopCount.setVisibility(View.GONE);
                        isBuy = true;
                    }
                }catch (Exception e){}
                mPayCorver.isBuyVideo(isBuy);

                // 是否可以订阅大师 1 可以订阅（可以订阅则不可以购买视频） 2 不能订阅 （不能订阅则可以购买视频）
                if("1".equals(detailBean.getIs_order())){
                    llBottomBtn.setVisibility(View.GONE);
                    tvSubscrib.setVisibility(View.VISIBLE);
                    ivRight.setVisibility(View.GONE);
                    tvShopCount.setVisibility(View.GONE);
                }else{
                    tvSubscrib.setVisibility(View.GONE);
                }

                if (detailBean.getIs_fans() == 1) {
                    llPraise.setSelected(true);
                } else {
                    llPraise.setSelected(false);
                }

                mVideoUrl = detailBean.getVideo().getVideo();
                setVideoPlayData(detailBean.getVideo().getTitle());

                tvVideoDetial.setText(detailBean.getVideo().getAbstractX());
                mShopCount = Integer.parseInt(detailBean.getNum());
                tvShopCount.setText(String.valueOf(mShopCount));//购物车数量
                tvVedioCategory.setText(detailBean.getVideo().getClassify_name());

                try {
                    mCommentsCount = Integer.parseInt(detailBean.getLeave_num());
                }catch (Exception e){}
                tvCommentCount.setText("热门评论（"+mCommentsCount+"）");
                if (detailBean.getLeave() != null) {//评论数据
                    commentData.clear();
                    commentData.addAll(detailBean.getLeave());
                    commentAdapter.notifyDataSetChanged();
                }
                if (detailBean.getHot() != null) {//推荐数据
                    mRankData.clear();
                    mRankData.addAll(detailBean.getHot());
                    rankingAdapter.notifyDataSetChanged();
                }

            }

        } else if (method == HttpMethod.HTTP_PUB_FABULOUS) {//点赞取消点赞
            if (llPraise.isSelected()) {
                //取消点赞时，调用该方法
                setResult(RESULT_OK);
            }
            llPraise.setSelected(!llPraise.isSelected());//改变点赞状态
        } else if (method == HttpMethod.HTTP_ORDER_ADD_SHOPPING) {//9.2视频/图书加购物车
            ResponseBean responseBean = GsonUtil.GsonToBean(data, ResponseBean.class);
            if (responseBean != null) {
                ToastUtil.makeLongText(this, "成功加入购物车");
                tvAddCart.setText("移除购物车");
                mShopCount++;
                tvShopCount.setText(String.valueOf(mShopCount));//购物车数量
                isAddCart = true;
                mCartId = responseBean.getShopping_id();
                isResult = !isResult;
                RxBus.getInstance().post(ConstantUserInfo.REFRESH_VIDEO_LIST);
            }
        } else if (method == HttpMethod.HTTP_USER_DEL_SHOPPING) {//8.13删除购物车商品
            ToastUtil.makeLongText(this, "成功移除购物车");
            removeCart();
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_VIDEO_LIST);
        } /*else if (method == HttpMethod.HTTP_YOUR_URL) {//获取支付参数
            try {
                JSONObject jsonObject = new JSONObject(data);
                if (jsonObject.has("error")) {
                    jsonObject = jsonObject.getJSONObject("error");
                    String message = jsonObject.getString("message");
                    dialogPrompt(message, null, "知道了").show();
                } else {
                    Pingpp.createPayment(this, data);//调起支付控件
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }*/ else if (method == HttpMethod.HTTP_ORDER_ORDER_VIDEO) {//9.3 购买图书/视频
            ToastUtil.makeLongText(this, "购买成功");
            setPayVideoPlay();
            mBuyCount++;
            setBuyCountView();
        }else if (method == HttpMethod.HTTP_ORDER_ORDER_APP) {//9.4定购大师/APP
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_SUBSCRIBE);
            ToastUtil.makeLongText(this, "订阅成功");
            tvSubscrib.setSelected(false);
            tvSubscrib.setText("已订阅");
        }
    }

    /**
     * 设置购买数量view
     */
    private void setBuyCountView() {
        String score = mBuyCount + "人购买";
        tvCount.setText(score);
    }

    /**
     * 移除购物车UI处理
     */
    private void removeCart() {
        tvAddCart.setText("加入购物车");
        mShopCount--;
        tvShopCount.setText(String.valueOf(mShopCount));//购物车数量
        isAddCart = false;
        mCartId = null;
        isResult = !isResult;
    }

    /**
     * 购买成功后，视频处理
     */
    private void setPayVideoPlay() {
        isBuy = true;
        llBottomBtn.setVisibility(View.GONE);
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        if (!StringUtils.isEmpty(message) && method != HttpMethod.HTTP_HANDPICK_VIDEO_PLAY) {
            ToastUtil.makeLongText(this, message);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        finishActivity();
        if(mVideoView.isInPlaybackState()){
            mVideoView.pause();
        }else{
            mVideoView.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mVideoView.getState()==STATE_PAUSED){
            if(mVideoView.isInPlaybackState()){
                if(!userPause)
                    mVideoView.resume();
            }else{
                mVideoView.rePlay(0);
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.stopPlayback();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SEEK_POSITION_KEY, mSeekPosition);
    }

    @Override
    protected void onRestoreInstanceState(Bundle outState) {
        super.onRestoreInstanceState(outState);
        mSeekPosition = outState.getInt(SEEK_POSITION_KEY);
        Log.d("Log", "onRestoreInstanceState Position=" + mSeekPosition);
    }

    @Override
    public void onBackPressed() {
        if (this.isLandscape) {
            ((ControllerCover)mReceiverGroup.getReceiver(KEY_CONTROLLER_COVER)).requestBack();
            updateVideo(false);
        } else {
            super.onBackPressed();
        }
    }

    private OnVideoViewEventHandler mOnEventAssistHandler = new OnVideoViewEventHandler(){
        @Override
        public void onAssistHandle(BaseVideoView assist, int eventCode, Bundle bundle) {
            super.onAssistHandle(assist, eventCode, bundle);
            switch (eventCode){
                case DataInter.Event.CODE_REQUEST_PAUSE://控制暂停
                    userPause = true;
                    break;
                case DataInter.Event.EVENT_CODE_REQUEST_BACK://返回按钮
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                case DataInter.Event.EVENT_CODE_REQUEST_TOGGLE_SCREEN://控制视屏横竖屏播放
                    setRequestedOrientation(isLandscape ?
                            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
                            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;
                case DataInter.Event.EVENT_CODE_ERROR_SHOW:
                    mVideoView.stop();
                    break;
            }
        }
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if(newConfig.orientation== Configuration.ORIENTATION_LANDSCAPE){
            isLandscape = true;
            updateVideo(true);
        }else{
            isLandscape = false;
            updateVideo(false);
        }

        mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_IS_LANDSCAPE, isLandscape);
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 视屏放大，横竖屏播放设置播放器
     * @param landscape
     */
    private void updateVideo(boolean landscape){
        FrameLayout.LayoutParams videoContainerParams = (FrameLayout.LayoutParams) mFlVideoContainer.getLayoutParams();
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mVideoView.getLayoutParams();
        RelativeLayout.LayoutParams topViewParam = (RelativeLayout.LayoutParams) flTopView.getLayoutParams();
        if(landscape){
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            videoContainerParams.setMargins(0, 0, 0, 0);
            videoContainerParams.height = layoutParams.height;

            topViewParam.topMargin = 0;
//            llBottomBtn.setVisibility(View.GONE);
            hideSystemUI();
//            systemBarTintManager.setStatusBarTintColor(Color.TRANSPARENT);
        }else{
            layoutParams.width = PUtil.getScreenW(this);
            layoutParams.height = layoutParams.width * 9/16;
            videoContainerParams.setMargins(0,DisplayUtil.dip2px(this,45), 0, 0);//设置标题栏的高度
            videoContainerParams.height = layoutParams.height;
            mFlVideoContainer.setLayoutParams(videoContainerParams);
            topViewParam.topMargin = statusBarHeight;//设置状态栏的高度
//            llBottomBtn.setVisibility(View.VISIBLE);
//            systemBarTintManager.setStatusBarTintColor(Color.WHITE);
            showSystemUI();
        }
        mVideoView.setLayoutParams(layoutParams);
    }
    /**
     * 隐藏菜单。沉浸式阅读
     */
    private void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        //  | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
    }

    private void showSystemUI() {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        );
    }
    @Override
    public void shareResultCallBack(int result) {
        switch (result) {
            case 1:
                HttpMethod.pubShare(this,this,mDetailId,"2");
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }

    /**
     * 获取视频详情数据
     */
    private void getVideoDetail() {
        loadWaitDialog();
        HttpMethod.videoDetails(this, this, mDetailId);
    }

    /**
     * 设置点赞状态
     *
     * @param type 1点赞2 取消
     */
    private void setVideoPraise(int type) {
        //loadWaitDialog();
        HttpMethod.pubFabulous(this, this,mDetailId, String.valueOf(type), "1");
    }

    /**
     * 加入购物车
     */
    private void addCart() {
//        loadWaitDialog();
        HttpMethod.addShopping(this, this, "1", mDetailId);
    }

    /**
     * 删除购物车
     */
    private void delCart() {
        if (!StringUtils.isEmpty(mCartId)) {
//            loadWaitDialog();
            HttpMethod.delShopping(this, this, mCartId,"2");
        }
    }

    /**
     * 5.8 用户停止视频播放
     */
    private void setVideoProgress() {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        mPlayPercentage = (float) mVideoView.getCurrentPosition()/mVideoView.getDuration();
        float playPercentage = mPlayPercentage * 100;
        if (isLogin && playPercentage > 0) {
            String percent = String.format("%.2f", playPercentage) + "%";
            HttpMethod.videoPlaysPercent(this, this, mDetailId, percent,String.valueOf(mPlayTime),"1",null);
        }
    }

    /**
     * 結束当前界面
     */
    private void finishActivity() {
        setVideoProgress();
        float playPercentage = mPlayPercentage * 100;
        String percent = String.format("%.2f", playPercentage) + "%";
        if (isResult || playPercentage > 0) {
            Intent intent = new Intent();
            if (playPercentage > 0) {
                intent.putExtra("percent", percent);
            }
            setResult(RESULT_OK, intent);
            RxBus.getInstance().post(REFRESH_STATE);
        }
    }

    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null != msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null != msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.create().show();
    }

}